package cn.edu.sgu.www.pms.service.impl;

import cn.edu.sgu.www.pms.consts.CustomMessages;
import cn.edu.sgu.www.pms.dto.EmailDTO;
import cn.edu.sgu.www.pms.entity.Email;
import cn.edu.sgu.www.pms.enums.OpenStatus;
import cn.edu.sgu.www.pms.mapper.EmailMapper;
import cn.edu.sgu.www.pms.service.EmailService;
import cn.edu.sgu.www.pms.util.ObjectUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class EmailServiceImpl implements EmailService {

    private final EmailMapper emailMapper;

    @Autowired
    public EmailServiceImpl(EmailMapper emailMapper) {
        this.emailMapper = emailMapper;
    }

    @Override
    public void enable(Integer id) {
        Email email = emailMapper.selectById(id);

        if (OpenStatus.UN_OPEN.getValue().equals(email.getState())) {
            // 批量修改state
            UpdateWrapper<Email> updateWrapper = new UpdateWrapper<>();

            updateWrapper.eq("user_id", email.getUserId());
            updateWrapper.set("state", OpenStatus.UN_OPEN.getValue());

            emailMapper.update(updateWrapper.getEntity(), updateWrapper);

            // 通过ID修改state
            updateWrapper.clear();

            updateWrapper.eq("id", id);
            updateWrapper.eq("state", OpenStatus.UN_OPEN.getValue());

            updateWrapper.set("state", OpenStatus.OPEN.getValue());

            emailMapper.update(updateWrapper.getEntity(), updateWrapper);
        }
    }

    @Override
    public void insert(EmailDTO emailDTO) {
        Email email = toEntity(emailDTO);

        email.setId(null);

        emailMapper.insert(email);
    }

    @Override
    public void deleteById(Integer id) {
        emailMapper.deleteById(id);
    }

    @Override
    public void updateById(EmailDTO emailDTO) {
        ObjectUtils.requireNonNull(emailDTO.getId(), CustomMessages.ID_NOT_NULL);

        Email email = toEntity(emailDTO);

        emailMapper.updateById(email);
    }

    @Override
    public List<Email> selectByUserId(String userId) {
        QueryWrapper<Email> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", userId);

        return emailMapper.selectList(queryWrapper);
    }

    private Email toEntity(EmailDTO emailDTO) {
        Email email = new Email();

        email.setId(emailDTO.getId());
        email.setState(emailDTO.getState());
        email.setUserId(emailDTO.getUserId());
        email.setAccount(emailDTO.getAccount());

        return email;
    }

}